//variables
var game = {
	editor: true,
	canvas: null,
	ctx: null,
	grid: 44,
	sheetGrid: 96, 
	p: new Player()
}

var fps = {
	FPSlimit: 60,
	fpsInterval: setInterval(updateFPS, 1000),
	curFPS: 0,
	numFramesDrawn: 0
}

var content = {
	mapLoaded: true,
	contentLoaded: false,
	numResourcesLoaded: 0,
	totalResources: 2,
	images: {},
	mapFiles: new Array(),
	level: {
		name: "Error 100 - Level not found",
		map: [,],
		spawnPos: {
			"x": 0,
	 		"y": 0
	 	}
	 }
}

var camera = {
	x: 150,
	y: 0,
	scale: 1
}

try {
    document.onload = init();
} catch(e) {
    stickyError(
        "An unknown error occurred!", e
    );
}
	
function init() {
	game.canvas = document.getElementById('canvas');
	game.ctx = game.canvas.getContext('2d');
	initListeners();
	loadContext();
	head.js("js/maps/map_003.js");
	setInterval(gameLoop, 1000/fps.FPSlimit);
}

function loadContext () {
	loadImage("TilesSprite1");
	loadImage("MaskSprite1");
}

function loadImage(name) {
  content.images[name] = new Image();
  content.images[name].onload = function() { 
	  resourceLoaded();
  }
  content.images[name].src = "img/" + name + ".png";
}

function resourceLoaded() {
  content.numResourcesLoaded += 1;
  if(content.numResourcesLoaded === content.totalResources) {
	content.contentLoaded = true;
  }
}

function gameLoop() {
	if (content.contentLoaded && content.mapLoaded) {
		update();
		clear();
		draw();
	} else {
		/*drawLoading();*/
	}
	++fps.numFramesDrawn;
}

function updateFPS() {
	fps.curFPS = fps.numFramesDrawn;
	fps.numFramesDrawn = 0;
}

function isPlaceFree(x, y) {
	var t = content.level.map[x][y];
	if (t.length > 0) {
		switch (t.charAt(0)) {
			case 'w':
			return false;
			break;
		}
	}
	return true;
}

function clear() {
	// Store the current transformation matrix
	game.ctx.save();
	// Use the identity matrix while clearing the canvas
	game.ctx.setTransform(1, 0, 0, 1, 0, 0);
	game.ctx.clearRect(0, 0, game.canvas.width, game.canvas.height);
	// Restore the transform
	game.ctx.restore();
}